<template>
  <y-dialog @open="open" @close="emit('close')" width="1000px" append-to-body>
    <el-form ref="addReqsRef" :model="form" size="default" label-width="120px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="选择需求" style="font-weight: bold">
            <el-checkbox
              v-model="reqExpand"
              @change="handleCheckedTreeExpand($event)"
              >展开/折叠
            </el-checkbox>
            <el-checkbox
              v-model="reqNodeAll"
              @change="handleCheckedTreeNodeAll($event)"
              >全选/全不选
            </el-checkbox>
            <el-checkbox
              v-model="reqCheckStrictly"
              @change="handleCheckedTreeConnect($event)"
              >父子联动
            </el-checkbox>
            <el-checkbox
              v-model="queryParams.showcase"
              @change="handleRelatedCases($event)"
              >关联用例
            </el-checkbox>
            <el-tree
              class="tree-border"
              :data="reqOptions"
              show-checkbox
              ref="reqTreeRef"
              node-key="id"
              :check-strictly="!reqCheckStrictly"
              empty-text="加载中，请稍候"
              :props="{ label: 'name', children: 'children' }"
            >
            </el-tree>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button type="warning" @click="reset">重置</el-button>
        <el-button @click="emit('close')">取消</el-button>
      </div>
    </template>
  </y-dialog>
</template>

<script setup name="AdReqs">
import { treeselect } from "@/api/pms/requirement";

const { proxy } = getCurrentInstance();

const emit = defineEmits(["submited", "close"]);

const reqOptions = ref([]);
const reqTreeRef = ref(null);
const reqExpand = ref(true);
const reqNodeAll = ref(false);
const reqCheckStrictly = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    showcase: true,
    product: undefined,
  },
});

const { queryParams, form } = toRefs(data);

const props = defineProps({
  id: { type: String, default: "" },
  getMethod: { type: Function, default: undefined },
  updateMethod: { type: Function, default: undefined },
});

/** 打开对话框事件 */
function open() {
  props.getMethod(props.id).then((res) => {
    form.value = res.data;
    nextTick(() => {
      queryParams.value.product = form.value.product.value;
      const casesNodes = treeselect(queryParams.value);
      casesNodes.then((response) => {
        reqOptions.value = response.data;
        let checkedKeys = form.value.requirements.concat(form.value.testcases);
        if (checkedKeys) {
          checkedKeys.forEach((v) => {
            nextTick(() => {
              reqTreeRef.value.setChecked(v.value, true, false);
            });
          });
        }
      });
    });
  });
}

/** 重置Form方法 */
function reset() {
  handleCheckedTreeNodeAll();
}

/** 提交按钮事件 */
function submit() {
  proxy.$refs["addReqsRef"].validate((valid) => {
    if (valid) {
      form.value.requirements = getAllCheckedKeys("Requirement");
      form.value.testcases = getAllCheckedKeys("TestCase");
      props.updateMethod(form.value).then((res) => {
        proxy.$modal.msgSuccess("添加成功");
        submited();
      });
    }
  });
}

/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value) {
  let treeList = reqOptions.value;
  for (let i = 0; i < treeList.length; i++) {
    reqTreeRef.value.store.nodesMap[treeList[i].id].expanded = value;
  }
}

/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value) {
  reqTreeRef.value.setCheckedNodes(value ? reqOptions.value : []);
}

/** 树权限（父子联动） */
function handleCheckedTreeConnect(value) {
  reqCheckStrictly.value != true;
}

/** 需求对应的用例节点 */
function handleRelatedCases(value) {
  queryParams.value.showcase != true;
  open();
}

/** 所有用例节点数据 */
function getAllCheckedKeys(nodeType) {
  // 目前被选中的用例节点
  let checkedKeys = [];
  let checkedNodes = reqTreeRef.value.getCheckedNodes();

  checkedNodes.forEach(function (node) {
    if (node.type == nodeType) {
      checkedKeys.push(node.id);
    }
  });

  // 半选中的用例节点
  let halfCheckedKeys = [];
  let halfCheckedNodes = reqTreeRef.value.getHalfCheckedNodes();
  halfCheckedNodes.forEach(function (node) {
    if (node.type == nodeType) {
      halfCheckedKeys.push(node.id);
    }
  });
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}

/** submited事件 */
function submited() {
  emit("submited");
  emit("close");
}
</script>
